<template>
  <el-dialog
    v-model="state.dialogFormVisible"
    :title="t('organization.organizationInfo')"
    custom-class="dialog-min-width"
    :destroy-on-close="true"
  >
    <el-form ref="formRef" :model="formEdit" :rules="rules" label-width="120px">
      <el-row>
        <el-col :lg="24" :md="24" :sm="24" :xs="24">
          <el-form-item
            :label="t('organization.orgFullCnName')"
            prop="orgFullCnName"
          >
            <el-input v-model="formEdit.orgFullCnName" maxlength="64" clearable>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :lg="24" :md="24" :sm="24" :xs="24">
          <el-form-item :label="t('organization.orgFullEnName')">
            <el-input v-model="formEdit.orgFullEnName" maxlength="64" clearable>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :lg="12" :md="12" :sm="24" :xs="24">
          <el-form-item :label="t('organization.orgName')" prop="orgName">
            <el-input v-model="formEdit.orgName" maxlength="64" clearable>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :lg="12" :md="12" :sm="24" :xs="24">
          <el-form-item :label="t('organization.orgCode')" prop="orgCode">
            <el-input v-model="formEdit.orgCode" maxlength="64" clearable>
            </el-input>
          </el-form-item>
        </el-col>

        <el-col :lg="24" :md="24" :sm="24" :xs="24">
          <el-form-item :label="t('organization.orgPaths')">
            <el-cascader
              v-if="state.dialogFormVisible"
              :props="orgProps"
              show-all-levels
              clearable
              class="fix-el-cascader-width-100"
              v-model="formEdit.orgPaths"
            />
          </el-form-item>
        </el-col>

        <el-col :lg="12" :md="12" :sm="24" :xs="24">
          <el-form-item prop="levelCode">
            <template #label>
              {{ t("organization.levelCode") }}
              <el-popover
                placement="top"
                :width="200"
                effect="dark"
                trigger="click"
                :content="t('organization.levelCodeContent')"
              >
                <template #reference>
                  <el-icon style="vertical-align: sub; cursor: pointer"
                    ><Warning
                  /></el-icon>
                </template>
              </el-popover>
            </template>
            <template #default>
              <el-input v-model="formEdit.levelCode" maxlength="64" clearable>
              </el-input
            ></template>
          </el-form-item>
        </el-col>

        <el-col :lg="12" :md="12" :sm="24" :xs="24">
          <el-form-item :label="t('organization.societyCode')">
            <el-input v-model="formEdit.societyCode" maxlength="32" clearable>
            </el-input>
          </el-form-item>
        </el-col>

        <el-col :lg="12" :md="12" :sm="24" :xs="24">
          <el-form-item :label="t('organization.contact')">
            <el-input v-model="formEdit.contact" maxlength="16" clearable>
            </el-input>
          </el-form-item>
        </el-col>

        <el-col :lg="12" :md="12" :sm="24" :xs="24">
          <el-form-item :label="t('organization.telephone')">
            <el-input v-model="formEdit.telephone" maxlength="16" clearable>
            </el-input>
          </el-form-item>
        </el-col>

        <el-col :lg="12" :md="12" :sm="24" :xs="24">
          <el-form-item :label="t('organization.address')">
            <el-input v-model="formEdit.address" maxlength="128" clearable>
            </el-input>
          </el-form-item>
        </el-col>

        <el-col :lg="12" :md="12" :sm="24" :xs="24">
          <el-form-item :label="t('organization.zipCode')">
            <el-input v-model="formEdit.zipCode" maxlength="16" clearable>
            </el-input>
          </el-form-item>
        </el-col>

        <el-col :lg="12" :md="12" :sm="24" :xs="24">
          <el-form-item :label="t('organization.extension0')">
            <el-input v-model="formEdit.extension0" maxlength="16" clearable>
            </el-input>
          </el-form-item>
        </el-col>

        <el-col :lg="12" :md="12" :sm="24" :xs="24">
          <el-form-item :label="t('organization.extension1')">
            <el-input v-model="formEdit.extension1" maxlength="16" clearable>
            </el-input>
          </el-form-item>
        </el-col>

        <el-col :lg="12" :md="12" :sm="24" :xs="24">
          <el-form-item :label="t('organization.extension2')">
            <el-input v-model="formEdit.extension2" maxlength="16" clearable>
            </el-input>
          </el-form-item>
        </el-col>

        <el-col :lg="12" :md="12" :sm="24" :xs="24">
          <el-form-item :label="t('organization.extension3')">
            <el-input v-model="formEdit.extension3" maxlength="16" clearable>
            </el-input>
          </el-form-item>
        </el-col>

        <el-col :lg="12" :md="12" :sm="24" :xs="24">
          <el-form-item :label="t('organization.extension4')">
            <el-input v-model="formEdit.extension4" maxlength="16" clearable>
            </el-input>
          </el-form-item>
        </el-col>

        <el-col :lg="12" :md="12" :sm="24" :xs="24">
          <el-form-item :label="t('organization.extension5')">
            <el-input v-model="formEdit.extension5" maxlength="16" clearable>
            </el-input>
          </el-form-item>
        </el-col>

        <el-col :lg="12" :md="12" :sm="24" :xs="24">
          <el-form-item :label="t('organization.category')">
            <el-radio-group v-model="formEdit.category">
              <!-- <el-radio :label="t('organization.categoryUnit')">{{
                t("organization.categoryUnit")
              }}</el-radio>
              <el-radio :label="t('organization.categoryDept')">{{
                t("organization.categoryDept")
              }}</el-radio> -->
              <template v-for="code in state.orgCategory">
                <!-- <el-radio :label="code.name">{{ code.name }}</el-radio> -->
                <el-radio :label="code.name">{{ code.name }}</el-radio>
              </template>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :lg="24" :md="24" :sm="24" :xs="24">
          <el-form-item :label="t('organization.status')">
            <el-switch
              v-model="formEdit.status"
              :active-value="1"
              :inactive-value="0"
            />
          </el-form-item>
        </el-col>
        <el-col :lg="24" :md="24" :sm="24" :xs="24">
          <el-form-item :label="t('organization.description')">
            <el-input
              v-model="formEdit.description"
              type="textarea"
              maxlength="64"
            >
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="state.dialogFormVisible = false">{{
          t("common.cancelButton")
        }}</el-button>
        <el-button type="primary" @click="handleSubmit">{{
          t("common.submitButton")
        }}</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { reactive, ref } from "vue";
import { Warning } from "@element-plus/icons-vue";
import apiOrganization from "../api/organization";
import utils from "../../../utils/utils";
import OrgTreeNode from "../organization/tree-node";
import { useI18n } from "vue-i18n";
import apiCode from "../api/code";
const { t } = useI18n({ useScope: "global" });
const formRef = ref();
const state = reactive({
  dialogFormVisible: false,
  orgCategory: Array<any>(<any>null),
});

const formEditOriginal = () => {
  return {
    orgId: "",
    parentId: "",
    orgName: "",
    orgFullCnName: "",
    orgFullEnName: "",
    orgCode: "",
    // 提交数据库，逗号分隔字符串
    orgPath: "",
    // 前台临时使用，绑定下拉树
    orgPaths: <any>null,
    levelCode: "",
    societyCode: "",
    category: "",
    contact: "",
    telephone: "",
    address: "",
    zipCode: "",
    status: 1,
    extension0: "",
    extension1: "",
    extension2: "",
    extension3: "",
    extension4: "",
    extension5: "",
    description: "",
  };
};
const formEdit = reactive(formEditOriginal());

const rules = reactive({
  orgFullCnName: [
    { required: true, message: () => t("common.required"), trigger: "blur" },
  ],
  orgName: [
    {
      required: true,
      message: () => t("common.required"),
      trigger: "blur",
    },
  ],
  orgCode: [
    {
      required: true,
      message: () => t("common.required"),
      trigger: "blur",
    },
  ],
  levelCode: [
    {
      required: true,
      message: () => t("common.required"),
      trigger: "blur",
    },
  ],
});

const emit = defineEmits<{
  (event: "on-submit-success", row: any): void;
}>();

const orgProps = {
  label: "orgName",
  value: "orgId",
  leaf: "leaf",
  checkStrictly: true,
  lazy: true,
  async lazyLoad(node: any, resolve: any) {
    if (node.level === 0) {
      let childs = await apiOrganization.loadChilds("0");
      let orgNodes = Array<OrgTreeNode>();
      Object.assign(orgNodes, childs);
      return resolve(orgNodes);
    } else {
      if (node.data.leaf) {
        resolve([]);
      }
      let childs = await apiOrganization.loadChilds(node.data.orgId);
      let orgNodes = Array<OrgTreeNode>();
      Object.assign(orgNodes, childs);
      return resolve(orgNodes);
    }
  },
};

const handleSubmit = async () => {
  // 处理业务逻辑，触发关闭事件
  await formRef.value.validate();

  formEdit.parentId = "";
  if (formEdit.orgPaths != null && formEdit.orgPaths.length > 0) {
    formEdit.parentId = formEdit.orgPaths[formEdit.orgPaths.length - 1];
    formEdit.orgPath = formEdit.orgPaths.join(",");
  } else {
    formEdit.parentId = "";
    formEdit.orgPath = "";
  }
  apiOrganization
    .updateOrganization(formEdit)
    .then((response: any) => {
      if (response.data.code == 200) {
        state.dialogFormVisible = false;
        utils.infoNotification(t("common.submitSuccess"));
        emit("on-submit-success", formEdit);
      }
    })
    .catch((err: any) => {
      utils.errorNotification(t("common.submitException"), err);
    });
};

const show = (row: any) => {
  // console.log(row);
  state.orgCategory = [];
  apiCode
    .queryChildrenByParentCode("ORG_CATEGORY")
    .then((response: any) => {
      if (response.data.code == 200) {
        Object.assign(state.orgCategory, response.data.data);
      }
    })
    .catch((err: any) => {
      utils.errorNotification(t("common.submitException"), err);
    });

  Object.assign(formEdit, formEditOriginal());
  if (row != undefined) {
    apiOrganization
      .getOrganization(row.orgId)
      .then((response: any) => {
        if (response.data.code == 200) {
          Object.assign(formEdit, response.data.data);

          // 扩展信息
          apiOrganization
            .getOrganizationExtension(row.orgId)
            .then((response: any) => {
              if (response.data.code == 200) {
                Object.assign(formEdit, response.data.data);
                if (formEdit.orgPath.length > 0) {
                  formEdit.orgPaths = formEdit.orgPath.split(",");
                }
              }
            })
            .catch((err: any) => {
              utils.errorNotification(t("common.submitException"), err);
            });
        }
      })
      .catch((err: any) => {
        utils.errorNotification(t("common.submitException"), err);
      });
  }

  state.dialogFormVisible = true;
  // 重置表单校验
  if (formRef.value) {
    formRef.value.resetFields();
  }
};

defineExpose({
  show,
});
</script>
